package com.example.czy.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 属性赋值工具
 * 描述：对象 属性复制
 * 背景：基于 springframework BeanUtils 封装
 * 适用：支持不同类间 Object、List、Set、MyBatisPlus Page 同类型同名属性复制
 *
 * @author czy
 * @date 2022-02-26 22:24
 **/
public class BeanUtil {
    /**
     * 对象 属性复制
     *
     * @param source the source bean
     * @param clazz  class to instantiate
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T result = null;
        try {
            result = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(source, result);
        return result;
    }


    /**
     * list集合 属性复制
     *
     * @param sourceList the source list
     * @param clazz      class to instantiate
     * @param <T>
     * @return
     */
    public static <T> List<T> copyProperties(List<?> sourceList, Class<T> clazz) {
        if (sourceList == null) {
            return null;
        }
        return sourceList.stream().map(item -> copyProperties(item, clazz)).collect(Collectors.toList());
    }


    /**
     * set集合 属性复制
     *
     * @param sourceSet the source set
     * @param clazz     class to instantiate
     * @param <T>
     * @return
     */
    public static <T> Set<T> copyProperties(Set<?> sourceSet, Class<T> clazz) {
        if (sourceSet == null) {
            return null;
        }
        return sourceSet.stream().map(item -> copyProperties(item, clazz)).collect(Collectors.toSet());
    }

    /**
     * MyBatis-Plus page属性复制
     *
     * @param sourcePage the source page
     * @param clazz      class to instantiate
     * @return
     */
    public static <T> Page<T> copyProperties(Page<?> sourcePage, Class<T> clazz) {
        if (sourcePage == null) {
            return null;
        }

        Page<T> result = copyProperties((Object) sourcePage, Page.class);
        result.setRecords(copyProperties(sourcePage.getRecords(), clazz));
        return result;
    }


}